//
//  MyViewController.m
//  CoreData
//
//  Created by ibokan on 14-11-4.
//  Copyright (c) 2014年 ibokan. All rights reserved.
//

#import "MyViewController.h"
#import "Person.h"
#import "AppDelegate.h"
#import "MyTableViewController.h"
@interface MyViewController ()
@property(strong,nonatomic)NSString *imagePath;
@end

@implementation MyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.updateBtn.enabled = NO;
    self.doneBtn.enabled = YES;
//    if (self.imageBtn.imageView == nil){
        [self.imageBtn setTintColor:[UIColor blueColor]];
//    }else{
//        [self.imageBtn setTintColor:[UIColor clearColor]];
//    }
    UIApplication *app = [UIApplication sharedApplication];
    AppDelegate *delegate= app.delegate ;
    self.managedObjectContext = delegate.managedObjectContext;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(imageChoosed:) name:@"IMAGE" object:nil];
    
    //从update而来
    if (self.name!=nil) {
        
        self.updateBtn.enabled = YES;
        self.doneBtn.enabled = NO;
        
        
        //获得实体名为Student所有数据
        NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
        
        //指定查询条件
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",self.name];
        
        [request setPredicate:predicate];
        
        self.person = [self.managedObjectContext executeFetchRequest:request error:nil][0];
        
//        if (self.person) {
        if (self.person.imagePath == nil) {
            self.imageBtn.tintColor = [UIColor blueColor];
        }else{
            self.imageBtn.tintColor = [UIColor clearColor];
            UIImage *img = [UIImage imageWithContentsOfFile:self.person.imagePath];
            [self.imageBtn setTintColor:[UIColor clearColor]];
            [self.imageBtn setBackgroundImage:img forState:UIControlStateNormal];
        }
            self.nameTextField.text =self.person.name;
            self.phoneNoTextField.text = self.person.phoneNo;
//        }
    }
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)imageChoosed:(NSNotification*)notification{
    
    NSDictionary *dic = [NSDictionary new];
    
    dic = notification.userInfo;
    NSString *path = [dic allValues][0];
    
    self.imagePath = path;
    
    UIImage *img = [UIImage imageWithContentsOfFile:path];
    
    [self.imageBtn setTintColor:[UIColor clearColor]];
    [self.imageBtn setBackgroundImage:img forState:UIControlStateNormal];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)done:(UIBarButtonItem *)sender {
    
    if (self.nameTextField.text.length == 0 || self.phoneNoTextField.text.length == 0) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入完善的资料" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
    }else{
        
        NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
        
        //指定查询条件
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",self.nameTextField.text];
        
        [request setPredicate:predicate];
        
        if ([self.managedObjectContext executeFetchRequest:request error:nil].count != 0) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"此人已经存在" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alertView show];
            self.phoneNoTextField.text = self.person.phoneNo;
        }else{
            self.person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
            self.person.imagePath = self.imagePath;
            self.person.name = self.nameTextField.text;
            self.person.phoneNo = self.phoneNoTextField.text;
            NSError *error;
            if ([self.managedObjectContext save:&error]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存完成" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
                
                
                NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:2];
                [dic setValue:self.person.name forKey:@"name"];
                 NSNotification * notification = [NSNotification notificationWithName:@"SAVE" object:self userInfo:dic];
                [[NSNotificationCenter defaultCenter]postNotification:notification];
                [self.navigationController popViewControllerAnimated:YES];
                self.imageBtn.tintColor = [UIColor blueColor];
            }else{
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"保存error" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
            }
         }
      }
}

- (IBAction)updateAllData:(UIButton *)sender {
#pragma 测试用字符串
//    NSString *str = self.person.name;
    
    
    
    self.person.imagePath = self.imagePath;
    self.person.name = self.nameTextField.text;
    self.person.phoneNo = self.phoneNoTextField.text;
    
#pragma 测试修改名字带来的错误
//    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
//    
//    //指定查询条件
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@",self.nameTextField.text];
//    
//    [request setPredicate:predicate];
//    
//    NSArray *arr = [self.managedObjectContext executeFetchRequest:request error:nil];
//    if (arr.count > 0) {
//        NSLog(@"%@",arr[0]);
//    }
#pragma 测试修改名字带来的错误
   //指定查询条件
//    predicate = [NSPredicate predicateWithFormat:@"name=%@",str];
//    
//    [request setPredicate:predicate];
//    
//    NSArray *arr1 = [self.managedObjectContext executeFetchRequest:request error:nil];
//    if (arr1.count > 0) {
//        NSLog(@"%@",arr1[0]);
//    }
    
    
    
    
    
    
    NSLog(@"%@",self.person.name);
    [self.managedObjectContext save:nil];
    [self.navigationController popViewControllerAnimated:YES];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"1"];
    NSNotification *not = [[NSNotification alloc]initWithName:@"1" object:nil userInfo:dic];
    [self.myTableViewController refreshTheData:not];
    self.imageBtn.tintColor = [UIColor blueColor];
}

-(void)dealloc{
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification removeObserver:self name:@"SAVE" object:nil];
    [notification removeObserver:self name:@"IMAGE" object:nil];
}




















@end
